#include <stdio.h>
#include "ConfigStruct.h"

char *get_value(char *line);
char *strip_newLine(char *line);

ReadConfig(char *file_name, struct ConfigStruct *configuration)
{
    char line [ 255 ];
    char *result;

    FILE *file = fopen(file_name, "r");
    while ( fgets ( line, sizeof (line), file ) != NULL )
    {
        char *found = strstr(line, "laddress");
        if(found != NULL)
        {
            result = strip_newLine(get_value(line));
            strcpy(configuration->laddress,result);
        }

        found = strstr(line, "raddress");
        if(found != NULL)
        {
            result = strip_newLine(get_value(line));
            strcpy(configuration->raddress,result);
        }

        found = strstr(line, "numtests");
        if(found != NULL)
        {
            result = get_value(line);
            configuration->num_tests = atoi(result);
        }

        found = strstr(line, "testrounds");
        if(found != NULL)
        {
            result = get_value(line);
            configuration->num_rounds = atoi(result);
        }

        found = strstr(line, "packetsize");
        if(found != NULL)
        {
            result = get_value(line);
            configuration->packet_size = atoi(result);
        }

        found = strstr(line, "numthreads");
        if(found != NULL)
        {
            result = get_value(line);
            configuration->num_threads = atoi(result);
        }

        found = strstr(line, "test");
        if(found != NULL)
        {
            result = strip_newLine(get_value(line));
            strcpy(configuration->test_to_run,result);
        }

    }
    fclose ( file );
}

char *get_value(char *line)
{
    char *copy = strdup(line);
    strtok(copy, ":");//we don't care about the first part
    char *result = strtok(NULL, ":");
    return result;
}


char *strip_newLine(char *line)
{
    char *result = (char *)calloc(strlen(line), sizeof(char));
    result[0] = line[0];

    int i = 0;
    for(i = 1; i < strlen(line); i++)
    {
        if(line[i] != '\n')
        {
            result[i]= line[i];
        }
    }

    return result;
}
